<?php
namespace app\api\controller;

use think\facade\Db;
use think\facade\Log;
use think\facade\Request;
use think\facade\Cache;

class AcceptIdenfy
{
    private $redis;

    public function __construct()
    {
        $this->redis = Cache::store('redis')->handler();
    }

    public function webhkIdenfy()
    {
        $params = Request::param();
        //记录日志
        $time   = getUtcTime(false);
        Log::write($params);
        Log::write("\n");

        if(!is_array($params)){
            $params = json_decode($params , true);
        }

        if(isset($params['scanRef'])){
            $scanRef   = $params['scanRef'];
            $id_number = $params['data']['docPersonalCode'] ?? '';
            $list = Db::name('user_veriff')->where('session_id', $scanRef)->find();
            if($list){
                $id         = $list['id'];
                $name       = $list['name'];
                $status    = $params['status']['overall'] ?? '';
                $user_id    = $list['user_id'];
                if(!empty($id_number)){
                    $check_id_number = Db::name('user')
                        ->where('id_card', $id_number)->find();
                    if($check_id_number){
                        Db::name('user_veriff')->where('id', $id)
                            ->update([
                                'is_rep' => 'error',
                                'id_number' => $id_number,
                                'remark' => '身份证号码已存在',
                            ]);
                    }else{
                        Db::name('user_veriff')->where('id', $id)
                            ->update([
                                'is_rep' => $status,
                                'id_number' => $id_number,
                            ]);
                        if($status == 'APPROVED'){
                            Db::name('user')->where('id', $user_id)
                                ->update([
                                    'name' => $name,
                                    'grade'=>1,
                                    'grade_new'=>3,
                                    'id_card' => $id_number
                                ]);
                        }
                    }
                }else{
                    Db::name('user_veriff')->where('id', $id)
                        ->update([
                            'is_rep' => 'error',
                            'remark' => 'idNumber is null',
                        ]);
                }
            }else{
                Log::write("scanRef is UnFind:{$scanRef}");
            }
        }else{
            Log::write("scanRef is null");
        }
        http_response_code(200);
        echo "success";
    }
}
